/* Function definitions for userled.h */
#include <iostream>
#include <fstream>
#include "userled.h"
using namespace std;

ofstream triggerStream;
ofstream brightnessStream;

const char TRIGGER_PATH[2][42] = {"/sys/class/leds/beagleboard::usr0/trigger",
                                  "/sys/class/leds/beagleboard::usr1/trigger"};
const char BRIGHTNESS_PATH[2][45] = {"/sys/class/leds/beagleboard::usr0/brightness",
                                     "/sys/class/leds/beagleboard::usr1/brightness"};

void ledInit(int ledNum)
{
    if ((ledNum < 0) || (ledNum > 1))
    {
        cerr << "Invalid ledNum: " << ledNum << " in function ledInit.\n";
        return;
    }
    else 
    {
        cout << "Writing 'none' to: " << TRIGGER_PATH[ledNum] << endl;
        triggerStream.open(TRIGGER_PATH[ledNum]);
        triggerStream << "none\n";
        triggerStream.close();
    }
}

void ledHeartbeat(int ledNum)
{
    if ((ledNum < 0) || (ledNum > 1))
    {
        cerr << "Invalid ledNum: " << ledNum << " in function ledHeartbeat.\n";
        return; 
    }
    else
    {
        cout << "Writing 'heartbeat' to: " << TRIGGER_PATH[ledNum] << endl;
        triggerStream.open(TRIGGER_PATH[ledNum]);
        triggerStream << "heartbeat\n";
        triggerStream.close();
    }
}

void ledOn(int ledNum)
{
    if ((ledNum < 0) || (ledNum > 1))
    {
        cerr << "Invalid ledNum: " << ledNum << " in function ledOn.\n";
        return;
    }
    else
    {
        ledInit(ledNum);
        cout << "Writing '1' to: " << BRIGHTNESS_PATH[ledNum] << endl;
        brightnessStream.open(BRIGHTNESS_PATH[ledNum]);
        brightnessStream << "1\n";
        brightnessStream.close();
    }
}

void ledOff(int ledNum)
{
    if ((ledNum < 0) || (ledNum > 1))
    {
        cerr << "Invalid ledNum: " << ledNum << " in function ledOff.\n";
        return;
    }
    else
    {
        cout << "Writing '0' to: " << BRIGHTNESS_PATH[ledNum] << endl;
        brightnessStream.open(BRIGHTNESS_PATH[ledNum]);
        brightnessStream << "0\n";
        brightnessStream.close();
    }
}

void ledError(int errNo)
{
    ledHeartbeat(0);
}


